package com.hyphenate.easeui.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;

import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMConversation.EMConversationType;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.model.DBHelper_hy;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.model.HyUserDao;
import com.hyphenate.easeui.model.UserEventBean;
import com.hyphenate.easeui.model.recordBean_hy;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.utils.HYDateUtils;
import com.hyphenate.easeui.widget.EaseConversationList.EaseConversationListHelper;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * conversation list adapter
 *
 */
public class EaseConversationAdapater extends BaseAdapter {
    private static final String TAG = "ChatAllHistoryAdapter";
    private List<EMConversation> conversationList;
    private List<EMConversation> copyConversationList;
    private ConversationFilter conversationFilter;
    private boolean notiyfyByFilter;

    final int TYPE_1 = 0;
    final int TYPE_2 = 1;
    //数据库存储
    private DBHelper_hy db=null;
    private recordBean_hy rb=null;
    private Context context;
    HashMap<String,String> map_nodata=new HashMap();
    public EaseConversationAdapater(Context context, int resource,
            List<EMConversation> objects) {
        conversationList = objects;
        copyConversationList = new ArrayList<EMConversation>();
        copyConversationList.addAll(objects);
        this.context=context;
        if(db==null){
            db=new DBHelper_hy(context);
            rb=new recordBean_hy();
        }
    }

    @Override
    public int getCount() {
        return conversationList.size()+3;
    }

    @Override
    public EMConversation getItem(int arg0) {
        if (arg0 < conversationList.size()) {
            return conversationList.get(arg0);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public int getItemViewType(int position) {
        if(position == 0||position==1||position==2) {
            return TYPE_1;
        }else{
            return TYPE_2;
        }

    }
    @Override
    public int getViewTypeCount() {
        // TODO Auto-generated method stub
        return 2;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int type = getItemViewType(position);
        if(type==TYPE_1){
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_msgdispich_top, parent, false);
            }
            ViewHolder_top holder = (ViewHolder_top) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder_top();
                holder.name = (TextView) convertView.findViewById(R.id.tv);
                holder.avatar = (ImageView) convertView.findViewById(R.id.img);
                holder.imgbottom1 = (ImageView) convertView.findViewById(R.id.item_msgdistop_bottom1);
                holder.imgbottom2 = (ImageView) convertView.findViewById(R.id.item_msgdistop_bottom2);
                convertView.setTag(holder);
            }
            if(position==0){
                holder.name.setText("系统通知");
                holder.avatar.setBackgroundResource(R.drawable.sys_msg_icon);
                holder.imgbottom1.setVisibility(View.VISIBLE);
                holder.imgbottom2.setVisibility(View.GONE);
            }else if(position==1){
                holder.name.setText("官方客服");
                holder.avatar.setBackgroundResource(R.drawable.msg_kefu);
                holder.imgbottom2.setVisibility(View.GONE);
                holder.imgbottom1.setVisibility(View.VISIBLE);
            }else if(position ==2){
                holder.name.setText("我的群组");
                holder.avatar.setBackgroundResource(R.drawable.pic_icon_mygroup);
                holder.imgbottom2.setVisibility(View.VISIBLE);
                holder.imgbottom1.setVisibility(View.GONE);
            }
        }else if(type==TYPE_2) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.ease_row_chat_history, parent, false);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.unreadLabel = (TextView) convertView.findViewById(R.id.unread_msg_number);
                holder.message = (TextView) convertView.findViewById(R.id.message);
                holder.time = (TextView) convertView.findViewById(R.id.time);
                holder.avatar = (ImageView) convertView.findViewById(R.id.avatar);
                holder.msgState = convertView.findViewById(R.id.msg_state);
                holder.list_itease_layout = (RelativeLayout) convertView.findViewById(R.id.list_itease_layout);
                holder.motioned = (TextView) convertView.findViewById(R.id.mentioned);
                convertView.setTag(holder);
            }
            //holder.list_itease_layout.setBackgroundResource(R.drawable.ease_mm_listitem);

            // get conversation
            EMConversation conversation = getItem(position-3);
            // get username or group id
            try {
            String username = conversation.conversationId();

            if (conversation.getType() == EMConversationType.GroupChat) {
                String groupId = conversation.conversationId();
                if (EaseAtMessageHelper.get().hasAtMeMsg(groupId)) {
                    holder.motioned.setVisibility(View.VISIBLE);
                } else {
                    holder.motioned.setVisibility(View.GONE);
                }
                // group message, show group avatar
                //holder.avatar.setImageResource(R.drawable.ease_group_icon);
                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("null", holder.avatar, options1);
                EMGroup group = EMClient.getInstance().groupManager().getGroup(username);
                if(group != null){
                    holder.name.setText(group != null ? group.getGroupName() : "");
                }else {
                    HyUserDao hyUserDao = rb.findMember_other(db, username);
                    if (hyUserDao != null) {
                        String nickname = hyUserDao.getNickname();
                        if (!TextUtils.isEmpty(nickname)) {
                            holder.name.setText(nickname);
                        }
                    }
                }



                } else if (conversation.getType() == EMConversationType.ChatRoom) {
                holder.avatar.setImageResource(R.drawable.ease_group_icon);
                EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(username);
                holder.name.setText(room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : "");
                holder.motioned.setVisibility(View.GONE);
            } else {
//            EaseUserUtils.setUserAvatar(getContext(), username, holder.avatar);
//            EaseUserUtils.setUserNick(username, holder.name);

                HyUserDao hyUserDao = rb.findMember_other(db, username);
                if (hyUserDao != null) {
                    String nickname = hyUserDao.getNickname();
                    String face = hyUserDao.getFaceimg();
                    if (!TextUtils.isEmpty(nickname)) {
                        holder.name.setText(nickname);
                    } else {
                        holder.name.setText("匿名用户");
                    }
                    //Glide.with(getContext()).load(face).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.ease_default_avatar).into(holder.avatar);
                    if (TextUtils.isEmpty(face)) {
                        face = "null";
                    }
                    com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(face, holder.avatar, options);


                } else {
                    holder.avatar.setImageResource(R.drawable.ease_default_avatar);
                    // com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("null", holder.avatar,options);
                    if (map_nodata.get(username) == null) {
                        map_nodata.put(username, username);
                        EventBus.getDefault().post(new UserEventBean(username, 0));
                    }
                }
                holder.motioned.setVisibility(View.GONE);
            }

            if (conversation.getUnreadMsgCount() > 0) {
                // show unread message count
                holder.unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount()));
                holder.unreadLabel.setVisibility(View.VISIBLE);
            } else {
                holder.unreadLabel.setVisibility(View.INVISIBLE);
            }

            if (conversation.getAllMsgCount() != 0) {
                // show the content of latest message
                EMMessage lastMessage = conversation.getLastMessage();
                String content = null;
                if (cvsListHelper != null) {
                    content = cvsListHelper.onSetItemSecondaryText(lastMessage);
                }
                holder.message.setText(EaseSmileUtils.getSmiledText(context, EaseCommonUtils.getMessageDigest(lastMessage, (context))),
                        BufferType.SPANNABLE);
                if (content != null) {
                    holder.message.setText(content);
                }
                holder.time.setText(HYDateUtils.getTimestampString(new Date(lastMessage.getMsgTime())));
                if (lastMessage.direct() == EMMessage.Direct.SEND && lastMessage.status() == EMMessage.Status.FAIL) {
                    holder.msgState.setVisibility(View.VISIBLE);
                } else {
                    holder.msgState.setVisibility(View.GONE);
                }
            }
            }catch (NullPointerException e){

            }
        }


        return convertView;
    }
    
    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        if(!notiyfyByFilter){
            copyConversationList.clear();
            copyConversationList.addAll(conversationList);
            notiyfyByFilter = false;
        }
    }
    

    public Filter getFilter() {
        if (conversationFilter == null) {
            conversationFilter = new ConversationFilter(conversationList);
        }
        return conversationFilter;
    }
    



    private class ConversationFilter extends Filter {
        List<EMConversation> mOriginalValues = null;

        public ConversationFilter(List<EMConversation> mList) {
            mOriginalValues = mList;
        }

        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();

            if (mOriginalValues == null) {
                mOriginalValues = new ArrayList<EMConversation>();
            }
            if (prefix == null || prefix.length() == 0) {
                results.values = copyConversationList;
                results.count = copyConversationList.size();
            } else {
                String prefixString = prefix.toString();
                final int count = mOriginalValues.size();
                final ArrayList<EMConversation> newValues = new ArrayList<EMConversation>();

                for (int i = 0; i < count; i++) {
                    final EMConversation value = mOriginalValues.get(i);
                    String username = value.conversationId();
                    
                    EMGroup group = EMClient.getInstance().groupManager().getGroup(username);
                    if(group != null){
                        username = group.getGroupName();
                    }else{
                        EaseUser user = EaseUserUtils.getUserInfo(username);
                        // TODO: not support Nick anymore
//                        if(user != null && user.getNick() != null)
//                            username = user.getNick();
                    }

                    // First match against the whole ,non-splitted value
                    if (username.startsWith(prefixString)) {
                        newValues.add(value);
                    } else{
                          final String[] words = username.split(" ");
                            final int wordCount = words.length;

                            // Start at index 0, in case valueText starts with space(s)
                            for (int k = 0; k < wordCount; k++) {
                                if (words[k].startsWith(prefixString)) {
                                    newValues.add(value);
                                    break;
                                }
                            }
                    }
                }

                results.values = newValues;
                results.count = newValues.size();
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            conversationList.clear();
            if (results.values != null) {
                conversationList.addAll((List<EMConversation>) results.values);
            }
            if (results.count > 0) {
                notiyfyByFilter = true;
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }

    private EaseConversationListHelper cvsListHelper;

    public void setCvsListHelper(EaseConversationListHelper cvsListHelper){
        this.cvsListHelper = cvsListHelper;
    }
    
    private static class ViewHolder {
        /** who you chat with */
        TextView name;
        /** unread message count */
        TextView unreadLabel;
        /** content of last message */
        TextView message;
        /** time of last message */
        TextView time;
        /** avatar */
        ImageView avatar;
        /** status of last message */
        View msgState;
        /** layout */
        RelativeLayout list_itease_layout;
        TextView motioned;
    }
    private static class ViewHolder_top {
        TextView name;
        ImageView avatar;
        ImageView imgbottom1,imgbottom2;
    }
    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .showImageOnLoading(R.drawable.ease_default_avatar)
            .showImageOnFail(R.drawable.ease_default_avatar)
            .showStubImage(R.drawable.ease_default_avatar)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();
    DisplayImageOptions options1 = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .showImageOnLoading(R.drawable.ease_group_icon)
            .showImageOnFail(R.drawable.ease_group_icon)
            .showStubImage(R.drawable.ease_group_icon)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();
}

